<template>
  <view>
    <view class="new_login_wrapper">
      <image class="bg_img" src="https://taxi.raxan.xyz/wechat/static/images/login_bg2024.png" alt="" />
      <view class=" _w-max _top _left _z-index-5 _pos-fixed _top _left"
        :style="{ 'background-color': 'rgba(255, 255, 255,' + 0 + ')' }">
        <view :style="{ width: '100%', height: recHeight }"></view>
        <view class="felx_c h_96 f_s_18" style="position: relative;height: 96rpx;"
          :style="{ color: 'rgb(' + 255 + ',' + 255 + ',' + 255 + ')' }">
          <view @click="back" style="position: absolute;left: 24rpx;top: 24rpx;">
            <image style="width: 48rpx;height: 48rpx;"
              :src="'https://taxi.raxan.xyz/wechat/static/images/store_detail/a-chevron-left.png'" mode="" />
          </view>
          登录
        </view>
      </view>

      <view class="new_login_content">
        <view style="height: 96rpx;"></view>
        <view :style="{ width: '100%', height: recHeight }"></view>
        <view class="login_title">登录您的账户</view>
        <view>
          <view class="list">
            <view class="item">
              <image class="icon" src="https://taxi.raxan.xyz/wechat/static/images/login_phone_2024.png"></image>
              <input class="input" type="text" :placeholder="$t(`输入手机号码`)" v-model="account" maxlength="11" />
            </view>
            <view class="item">
              <image class="icon" src="https://taxi.raxan.xyz/wechat/static/images/login_ys_2021.png"></image>
                <input class="input" type="text" :placeholder="$t(`填写验证码`)" maxlength="6" v-model="captcha" />
                <button class="code" :disabled="disabled" :class="disabled === true ? 'on' : ''" @click="code">
                  {{ text }}
                </button>
            </view>
          </view>
          <view class="logon" @click="loginMobile">{{ $t(`登录`) }}</view>
          <view class="appLogin" style="margin-top: 24rpx;" v-if="!appLoginStatus && !appleLoginStatus">
            <view class="hds">
              <span class="line"></span>
              <p>{{ $t(`其他方式登录`) }}</p>
              <span class="line"></span>
            </view>
            <view class="btn-wrapper">
              <view class="btn wx" @click="wxLogin">
                <span class="iconfont icon-s-weixindenglu1"></span>
              </view>
            </view>
          </view>
          <view class="protocol">
            <checkbox-group @change='ChangeIsDefault'>
              <checkbox
                :class="inAnimation ? 'trembling' : ''"
                @animationend='inAnimation = false'
                :checked="protocol ? true : false"
              />
              {{ $t(`已阅读并同意`) }}
              <text style="color: #008DFF;" @click="privacy(4)">{{ $t(`《用户协议》`) }}</text>
              {{ $t(`与`) }}
              <text style="color: #008DFF;" @click="privacy(3)">{{ $t(`《隐私协议》`) }}</text>
            </checkbox-group>
          </view>
        </view>
      </view>
      <Verify @success="success" :captchaType="'blockPuzzle'" :imgSize="{ width: '330px', height: '155px' }" ref="verify"></Verify>
    </view>
  </view>

</template>
<script>
import sendVerifyCode from "@/mixins/SendVerifyCode";

import {
  loginH5,
  loginMobile,
  registerVerify,
  register,
  getCodeApi,
  getUserInfo,
  appleLogin
} from "@/api/user";

import {
  getLogo
} from "@/api/public";
// import cookie from "@/utils/store/cookie";
import {
  VUE_APP_API_URL
} from "@/utils";
// #ifdef APP-PLUS
import {
  wechatAppAuth
} from '@/api/api.js'
// #endif
const BACK_URL = "login_back_url";
import colors from '@/mixins/color.js';
import Verify from '../components/verify/index.vue';
export default {
  name: "Login",
  components: {
    Verify
  },
  mixins: [sendVerifyCode, colors],
  data: function () {
    return {
      recHeight: '',
      copyRight: '',
      inAnimation: false,
      protocol: false,
      navList: [this.$t(`快速登录`), this.$t(`账号登录`)],
      current: 1,
      account: "",
      password: "",
      captcha: "",
      formItem: 1,
      type: "login",
      logoUrl: "",
      keyCode: "",
      codeUrl: "",
      codeVal: "",
      isShowCode: false,
      appLoginStatus: false, // 微信登录强制绑定手机号码状态
      appUserInfo: null, // 微信登录保存的用户信息
      appleLoginStatus: false, // 苹果登录强制绑定手机号码状态
      appleUserInfo: null,
      appleShow: false, // 苹果登录版本必须要求ios13以上的
      keyLock: true
    };
  },
  watch: {
    formItem: function (nval, oVal) {
      if (nval == 1) {
        this.type = 'login'
      } else {
        this.type = 'register'
      }
    }
  },
  onLoad() {
    let self = this
    uni.getSystemInfo({
      success: (res) => {
        if (res.platform.toLowerCase() == 'ios' && this.getSystem(res.system)) {
          self.appleShow = true
        }
      }
    });
    if (uni.getStorageSync('copyRight').copyrightContext) {
      this.copyRight = uni.getStorageSync('copyRight').copyrightContext
    }

    this.getPhoneInfo();
  },
  mounted: function () {
    // this.getCode();
    this.getLogoImage();
  },
  methods: {
    back() {
      uni.navigateBack()
    },
    ChangeIsDefault(e) {
      this.$set(this, 'protocol', !this.protocol);
    },
    privacy(type) {
      uni.navigateTo({
        url: "/pages/users/privacy/index?type=" + type
      })
    },
    // IOS 版本号判断
    getSystem(system) {
      let str
      system.toLowerCase().indexOf('ios') === -1 ? str = system : str = system.split(' ')[1]
      if (str.indexOf('.'))
        return str.split('.')[0] >= 13
      return str >= 13
    },
    // 苹果登录
    appleLogin() {
      let self = this
      this.account = ''
      this.captcha = ''
      if (!self.protocol) {
        this.inAnimation = true
        return self.$util.Tips({
          title: '请先阅读并同意协议'
        });
      }
      uni.showLoading({
        title: this.$t(`登录中`)
      })
      uni.login({
        provider: 'apple',
        timeout: 10000,
        success(loginRes) {
          uni.getUserInfo({
            provider: 'apple',
            success: function (infoRes) {
              self.appleUserInfo = infoRes.userInfo
              self.appleLoginApi()
            },
            fail() {
              uni.showToast({
                title: self.$t(`获取用户信息失败`),
                icon: 'none',
                duration: 2000
              })
            },
            complete() {
              uni.hideLoading()
            }
          });
        },
        fail(error) {

        }
      })
    },
    // 苹果登录Api
    appleLoginApi() {
      let self = this
      appleLogin({
        openId: self.appleUserInfo.openId,
        email: self.appleUserInfo.email || '',
        phone: this.account,
        captcha: this.captcha
      }).then(({
        data
      }) => {
        if (data.isbind) {
          uni.showModal({
            title: self.$t(`提示`),
            content: self.$t(`请绑定手机号后，继续操作`),
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                self.current = 1
                self.appleLoginStatus = true
              }
            }
          });
        } else {
          self.$store.commit("LOGIN", {
            'token': data.token,
            'time': data.expires_time - self.$Cache.time()
          });
          let backUrl = self.$Cache.get(BACK_URL) || "/pages/car_index/index";
          self.$Cache.clear(BACK_URL);
          self.$store.commit("SETUID", data.userInfo.uid);
          uni.reLaunch({
            url: backUrl
          });
        }
      }).catch(error => {
        uni.showModal({
          title: self.$t(`提示`),
          content: self.$t(`错误信息`) + `${error}`,
          success: function (res) {
            if (res.confirm) {

            } else if (res.cancel) {

            }
          }
        });
      })
    },
    // App微信登录
    wxLogin() {
      let self = this
      this.account = ''
      this.captcha = ''
      if (!self.protocol) {
        this.inAnimation = true
        return self.$util.Tips({
          title: '请先阅读并同意协议'
        });
      }
      uni.showLoading({
        title: self.$t(`登录中`)
      })
      uni.login({
        provider: 'weixin',
        success: function (loginRes) {
          // 获取用户信息
          uni.getUserInfo({
            provider: 'weixin',
            success: function (infoRes) {
              self.appUserInfo = infoRes.userInfo
              self.wxLoginApi()
            },
            fail() {
              uni.showToast({
                title: self.$t(`获取用户信息失败`),
                icon: 'none',
                duration: 2000
              })
            },
            complete() {
              uni.hideLoading()
            }
          });
        },
        fail(err) {
          uni.showToast({
            title: JSON.stringify(err),
            icon: 'none',
            duration: 2000
          })
        }
      });
    },

    wxLoginApi() {
      let self = this
      wechatAppAuth({
        userInfo: self.appUserInfo,
        phone: this.account,
        code: this.captcha
      }).then(({
        data
      }) => {
        if (data.isbind) {
          uni.showModal({
            title: self.$t(`提示`),
            content: self.$t(`请绑定手机号后，继续操作`),
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                self.current = 1
                self.appLoginStatus = true
              }
            }
          });
        } else {
          self.$store.commit("LOGIN", {
            'token': data.token,
            'time': data.expires_time - self.$Cache.time()
          });
          let backUrl = self.$Cache.get(BACK_URL) || "/pages/car_index/index";
          self.$Cache.clear(BACK_URL);
          self.$store.commit("SETUID", data.userInfo.uid);
          uni.reLaunch({
            url: backUrl
          });
        }
      }).catch(error => {
        uni.showModal({
          title: self.$t(`提示`),
          content: self.$t(`错误信息`) + `${error}`,
          success: function (res) {
            if (res.confirm) {

            } else if (res.cancel) {

            }
          }
        });
      })
    },
    again() {
      this.codeUrl =
        VUE_APP_API_URL +
        "/sms_captcha?" +
        "key=" +
        this.keyCode +
        Date.parse(new Date());
    },
    success(data) {
      this.$refs.verify.hide()
      getCodeApi()
        .then(res => {
          this.keyCode = res.data.key;
          this.getCode(data);
        })
        .catch(res => {
          this.$util.Tips({
            title: res
          });
        });
    },
    code() {
      let that = this
      if (!that.protocol) {
        this.inAnimation = true
        return that.$util.Tips({
          title: '请先阅读并同意协议'
        });
      }
      if (!that.account) return that.$util.Tips({
        title: that.$t(`请填写手机号码`)
      });
      if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(that.account)) return that.$util.Tips({
        title: that.$t(`请输入正确的手机号码`)
      });
      this.$refs.verify.show()
    },
    async getLogoImage() {
      let that = this;
      getLogo(2).then(res => {
        that.logoUrl = res.data.logo_url;
      });
    },
    async loginMobile() {
      let that = this;
      if (!that.protocol) {
        this.inAnimation = true
        return that.$util.Tips({
          title: '请先阅读并同意协议'
        });
      }
      if (!that.account) return that.$util.Tips({
        title: that.$t(`请填写手机号码`)
      });
      if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(that.account)) return that.$util.Tips({
        title: that.$t(`请输入正确的手机号码`)
      });
      if (!that.captcha) return that.$util.Tips({
        title: that.$t(`请填写验证码`)
      });
      if (!/^[\w\d]+$/i.test(that.captcha)) return that.$util.Tips({
        title: that.$t(`请输入正确的验证码`)
      });
      if (that.appLoginStatus) {
        that.wxLoginApi()
      } else if (that.appleLoginStatus) {
        that.appleLoginApi()
      } else {
        if (this.keyLock) {
          this.keyLock = !this.keyLock
        } else {
          return that.$util.Tips({
            title: that.$t(`请勿重复点击`)
          });
        }
        loginMobile({
          phone: that.account,
          captcha: that.captcha,
          spread: that.$Cache.get("spread")
        })
          .then(res => {
            let data = res.data;
            that.$store.commit("LOGIN", {
              'token': data.token,
              'time': data.expires_time - this.$Cache.time()
            });
            let backUrl = that.$Cache.get(BACK_URL) || "/pages/car_index/index";
            that.$Cache.clear(BACK_URL);
            getUserInfo().then(res => {
              this.keyLock = true
              that.$store.commit("SETUID", res.data.uid);
              if (backUrl.indexOf('/pages/users/login/index') !== -1) {
                backUrl = '/pages/car_index/index';
              }
              uni.reLaunch({
                url: backUrl
              });
            })
          })
          .catch(res => {
            this.keyLock = true
            that.$util.Tips({
              title: res
            });
          });
      }

    },
    async register() {
      let that = this;
      if (!that.protocol) {
        this.inAnimation = true
        return that.$util.Tips({
          title: '请先阅读并同意协议'
        });
      }
      if (!that.account) return that.$util.Tips({
        title: that.$t(`请填写手机号码`)
      });
      if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(that.account)) return that.$util.Tips({
        title: that.$t(`请输入正确的手机号码`)
      });
      if (!that.captcha) return that.$util.Tips({
        title: that.$t(`请填写验证码`)
      });
      if (!/^[\w\d]+$/i.test(that.captcha)) return that.$util.Tips({
        title: that.$t(`请输入正确的验证码`)
      });
      if (!that.password) return that.$util.Tips({
        title: that.$t(`请填写密码`)
      });
      if (/^([0-9]|[a-z]|[A-Z]){0,6}$/i.test(that.password)) return that.$util.Tips({
        title: that.$t(`您输入的密码过于简单`)
      });
      register({
        account: that.account,
        captcha: that.captcha,
        password: that.password,
        spread: that.$Cache.get("spread")
      })
        .then(res => {
          that.$util.Tips({
            title: res
          });
          that.formItem = 1;
        })
        .catch(res => {
          that.$util.Tips({
            title: res
          });
        });
    },
    async getCode(data) {
      let that = this;
      if (!that.protocol) {
        this.inAnimation = true
        return that.$util.Tips({
          title: '请先阅读并同意协议'
        });
      }
      if (!that.account) return that.$util.Tips({
        title: that.$t(`请填写手机号码`)
      });
      if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(that.account)) return that.$util.Tips({
        title: that.$t(`请输入正确的手机号码`)
      });
      if (that.formItem == 2) that.type = "register";

      await registerVerify({
        phone: that.account,
        type: that.type,
        key: that.keyCode,
        captchaType: 'blockPuzzle',
        captchaVerification: data.captchaVerification
      })
        .then(res => {
          this.sendCode()
          that.$util.Tips({
            title: res.msg
          });
        })
        .catch(res => {
          that.$util.Tips({
            title: res
          });
        });
    },
    navTap: function (index) {
      this.current = index;
    },
    async submit() {
      let that = this;
      if (!that.protocol) {
        this.inAnimation = true
        return that.$util.Tips({
          title: '请先阅读并同意协议'
        });
      }
      if (!that.account) return that.$util.Tips({
        title: that.$t(`请填写账号`)
      });
      if (!/^[\w\d]{5,16}$/i.test(that.account)) return that.$util.Tips({
        title: that.$t(`请输入正确的账号`)
      });
      if (!that.password) return that.$util.Tips({
        title: that.$t(`请填写密码`)
      });
      if (this.keyLock) {
        this.keyLock = !this.keyLock
      } else {
        return that.$util.Tips({
          title: that.$t(`请勿重复点击`)
        });
      }
      loginH5({
        account: that.account,
        password: that.password,
        spread: that.$Cache.get("spread")
      })
        .then(({
          data
        }) => {
          that.$store.commit("LOGIN", {
            'token': data.token,
            'time': data.expires_time - this.$Cache.time()
          });
          let backUrl = that.$Cache.get(BACK_URL) || "/pages/car_index/index";
          that.$Cache.clear(BACK_URL);
          getUserInfo().then(res => {
            this.keyLock = true
            that.$store.commit("SETUID", res.data.uid);
            uni.reLaunch({
              url: backUrl
            });
          }).catch(error => {
            this.keyLock = true
          })
        })
        .catch(e => {
          this.keyLock = true
          that.$util.Tips({
            title: e
          });
        });
    },
    // 获取顶部高度信息
    getPhoneInfo() {
      uni.getSystemInfo({
        success: (res) => {
          this.recHeight = res.statusBarHeight + 'px'; //获取手机状态栏高度
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.felx_c {
  display: flex;
  align-items: center;
  justify-content: center;
}

.f_s_18 {
  font-size: 36rpx;
}

.new_login_wrapper {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  position: relative;
  .protocol {
      position: fixed;
      z-index: 999;
      bottom: 50rpx;
      left: 0;
      right: 0;
      color: #FFFFFF;
      font-size: 24rpx;
      text-align: center;
      font-weight: bold;
    }

  .bg_img {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0;
    z-index: 0;
  }
  .trembling {
    animation: shake 0.6s;
  }
  .new_login_content {
    width: 100vw;
    height: 100vh;
    overflow: hidden;
    position: absolute;
    padding: 0 48rpx;
    z-index: 1;
    left: 0;
    top: 0;

    .login_title {
      margin-top: 156rpx;
      margin-bottom: 76rpx;
      font-family: PingFang SC, PingFang SC;
      font-weight: bold;
      font-size: 48rpx;
      color: #022E57;
      line-height: 48rpx;
      text-align: center;
      font-style: normal;
      text-transform: none;
    }

    .list {
      .item {
        height: 112rpx;
        background: #FFFFFF;
        border-radius: 61rpx;
        border: 4rpx solid #F8F8F8;
        display: flex;
        align-items: center;
        justify-content: flex-start;
        padding: 0 48rpx;
        gap: 28rpx;
        margin-bottom: 32rpx;
        .icon {
          width: 48rpx;
          flex: 0 0 48rpx;
          height: 48rpx;
        }

        .input {
          flex: 1;
        }

        .code {
          width: 180rpx;
          flex: 0 0 180rpx;
          font-family: PingFang SC, PingFang SC;
          font-weight: 400;
          font-size: 36rpx;
          color: #008DFF;
          line-height: 44rpx;
        }
      }
    }
  }

  .hds {
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 24rpx;
    color: #FFFFFF;

    .line {
      width: 68rpx;
      height: 1rpx;
      background: #FFFFFF;
    }

    p {
      margin: 0 20rpx;
    }
  }

  .logon {
    line-height: 112rpx;
    text-align: center;
    background: #008DFF;
    border-radius: 61rpx;
    font-family: PingFang SC, PingFang SC;
    font-weight: bold;
    font-size: 36rpx;
    color: #FFFFFF;
  }
  .btn-wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 30rpx;

    .btn {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 68rpx;
      height: 68rpx;
      border-radius: 50%;
    }

    .apple-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 68rpx;
      height: 68rpx;
      border-radius: 50%;
      background: #000;


      .icon-s-pingguo {
        color: #fff;
        font-size: 44rpx;
      }
    }

    .iconfont {
      font-size: 40rpx;
      color: #fff;
    }

    .wx {
      margin-right: 30rpx;
      background-color: #61C64F;
    }

    .mima {
      margin-right: 30rpx;
      background-color: #28B3E9;
    }

    .yanzheng {
      margin-right: 30rpx;
      background-color: #F89C23;
    }

  }
}

</style>